package com.hnyc.service.impl;

import com.hnyc.domain.CandConstants;
import com.hnyc.domain.CandRole;
import com.hnyc.domain.CandUser;
import com.hnyc.exception.ServiceException;
import com.hnyc.mapper.CandUserMapper;
import com.hnyc.mapper.CandUserRoleMapper;
import com.hnyc.service.ICandUserService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;

/**
 * @Author: XieYingHao
 * @date: 2023/7/1 11:06
 */
@Service
public class CandUserServiceImpl implements ICandUserService {

    @Resource
    private CandUserMapper candUserMapper;

    @Resource
    private CandUserRoleMapper candUserRoleMapper;

    /**
     * 校验用户名称是否唯一
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    public String checkUserNameUnique(CandUser user) {
        Long userId = Objects.isNull(user.getId()) ? -1L : user.getId();
        CandUser info = candUserMapper.checkUserNameUnique(user.getUserName());
        if (!Objects.isNull(info) && info.getId().longValue() != userId.longValue()) {
            return CandConstants.NOT_UNIQUE;
        }
        return CandConstants.UNIQUE;
    }

    /**
     * 新增保存用户信息
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insertUser(CandUser user) {
        // 新增用户信息
        return candUserMapper.insertUser(user);
    }

    /**
     * 修改用户信息
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    public int updateUser(CandUser user){
        return candUserMapper.updateUser(user);
    }

    /**
     * 根据条件查询用户列表
     *
     * @param candUser 用户信息
     * @return 用户信息集合信息
     */
    @Override
    public List<CandUser> selectUserList(CandUser candUser) {
        return candUserMapper.selectUserList(candUser);
    }

    /**
     * 通过用户ID查询用户
     *
     * @param userId 用户ID
     * @return 结果
     */
    @Override
    public CandUser selectUserById(Long userId)
    {
        return candUserMapper.selectUserById(userId);
    }


    /**
     * 通过用户ID删除用户
     *
     * @param userId 用户ID
     * @return 用户对象信息
     */
    @Override
    @Transactional(rollbackFor=Exception.class)
    public int deleteUserById(Long userId) {
        CandUser user = selectUserById(userId);
        if (candUserRoleMapper.countUserRoleByUserId(userId) > 0)
        {
            throw new ServiceException(String.format("%1$s已分配,不能删除", user.getUserName()));
        }
        return candUserMapper.deleteUserById(userId);
    }
}
